package org.qloudgen.borg.pages.panel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.util.lang.Bytes;
import org.qloudgen.borg.beans.FileUploadBean;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class DSFileUploadPanel extends Panel {

	private static final long serialVersionUID = 1L;
	static Log log = LogFactory.getLog(DSFileUploadPanel.class);
	
	public DSFileUploadPanel(String id,final String labelString) {
		
		super(id);
		
		final FileUploadField image = new FileUploadField("image");
		image.setOutputMarkupId(true);
		
		final TextArea<String> contents = new TextArea<String>("contents");
		contents.setOutputMarkupId(true);
		
		final Form form = new Form("panel") {

			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit() {
				
				FileUploadBean bean = (FileUploadBean)getDefaultModelObject();
				final FileUpload upload = image.getFileUpload();

				if (upload != null) {
					StringBuffer sb = new StringBuffer();
					sb.append(new String(upload.getBytes()));
					bean.setContents(sb.toString());
				} 				
			}
		};
		
		form.setDefaultModel(new CompoundPropertyModel(new FileUploadBean().setLabel(labelString)));
		form.setOutputMarkupId(true);
		
		this.add(form);
		
		form.add(new Label("label"));
		form.add(contents);
		form.add(image);
		
		form.setMultiPart(true);
		form.setMaxSize(Bytes.kilobytes(1000));
		
		AjaxFormSubmitBehavior ajaxFormSubmitBehavior =  new AjaxFormSubmitBehavior(labelString){

			private static final long serialVersionUID = 1L;

			protected  void	onAfterSubmit(AjaxRequestTarget target) {
				target.add(form);
			}
		};
		form.add(ajaxFormSubmitBehavior);
		
		form.add(new Button("submit"));
	}

}


